package com.hxs.email.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.RSAPublicKeySpec;
import java.util.Base64;

public class PasswordEncryptionUtil {

    private static final Logger log = LoggerFactory.getLogger(PasswordEncryptionUtil.class);

    /**
     * 对密码进行RSA加密
     * @param pwd 原始密码
     * @param n RSA公钥模数（Base64编码）
     * @param e RSA公钥指数（Base64编码）
     * @return 加密后的密码（Base64编码）
     */
    public static String encryptPassword(String pwd, String n, String e) {
        try {
            // 解码Base64格式的n和e
            byte[] nBytes = Base64.getDecoder().decode(n);
            byte[] eBytes = Base64.getDecoder().decode(e);
            
            // 将字节数组转换为十六进制字符串，然后转换为BigInteger
            String nHex = bytesToHex(nBytes);
            String eHex = bytesToHex(eBytes);
            
            // 创建RSA公钥
            RSAPublicKeySpec keySpec = new RSAPublicKeySpec(
                new BigInteger(nHex, 16),
                new BigInteger(eHex, 16)
            );
            
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PublicKey publicKey = keyFactory.generatePublic(keySpec);
            
            // 加密
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] encryptedBytes = cipher.doFinal(pwd.getBytes());
            
            // Base64编码
            String result = Base64.getEncoder().encodeToString(encryptedBytes);
            return result;
            
        } catch (Exception ex) {
            throw new RuntimeException("Password encryption failed", ex);
        }
    }
    
    /**
     * 将字节数组转换为十六进制字符串
     */
    private static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }
}